import { defineStore } from 'pinia'
import { store } from '../index'
/**
 * h5 向 app 发送的消息体类型
 */
export interface MessageDetail {
  action: string
  message?: string
  uniCallbackFn?: string
}
/**
 * uniStore state类型
 */
export interface UniState {
  receiveData?: any
}

export const useUniStore = defineStore('pinia-uni', {
  state: (): UniState => {
    return {
      receiveData: undefined,
    }
  },
  actions: {
    init() {
      window.uniCallbackFn ??= (message: any) => {
        console.log('收到app消息: ', message)
        this.receiveData = message
      }
    },
    postMessage(detail: MessageDetail) {
      this.init()
      window.uni.postMessage({
        data: {
          ...detail,
          uniCallbackFn: detail.uniCallbackFn || 'window.uniCallbackFn',
        },
      })
    },
    scanCode() {
      this.postMessage({
        action: 'scanCode',
      })
    },
    logoutReset() {
      this.$reset()
    },
  },
  // 自动缓存 default：localStorage
  persist: false,
})

export function useUniStoreWithOut() {
  return useUniStore(store)
}
